package com.hp.gxw.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hp.gxw.constant.LayTableR;
import com.hp.gxw.constant.R;
import com.hp.gxw.entity.*;
import com.hp.gxw.exception.BusinessException;
import com.hp.gxw.mapper.SettleOrderMasterNewMapper;
import com.hp.gxw.service.*;
import com.hp.gxw.utils.Column;
import com.hp.gxw.utils.ConditionUtil;
import com.hp.gxw.utils.ExcelTool;
import com.hp.gxw.utils.TitleEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huangping
 * @since 2023-10-17
 */
@Controller
@RequestMapping("/manage/sale_order")
@Slf4j
public class SaleOrderController {

    @Autowired
    private ISaleOrderService iSaleOrderService;

    @Autowired
    private ISaleOrderDetailsService iSaleOrderDetailsService;

    @Autowired
    private ISaleOrderProcessService iSaleOrderProcessService;

    @Autowired
    private IProcessPriceOrderService iProcessPriceOrderService;

    @Autowired
    private ICustomerService iCustomerService;

    @Resource
    private ISettleOrderMasterNewService iSettleOrderMasterNewService;

    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("customer", iCustomerService.list());
        return "sale_order/index";
    }

    @RequestMapping("/addHtml")
    public String addHtml(Model model){
        return "sale_order/add";
    }

    @RequestMapping("/addDetailHtml")
    public String addDetailHtml(Model model){
        return "sale_order_details/add";
    }

    @RequestMapping("/addProcessHtml")
    public String addProcessHtml(Model model){
        return "sale_order_process/add";
    }

    @RequestMapping("/settleHtml")
    public String settleHtml(Model model){
        return "sale_order_process/add";
    }

    @RequestMapping("/infoHtml")
    public String infoHtml(String id, Model model){
        model.addAttribute("id", id);
        return "sale_order/info";
    }

    @RequestMapping("/list")
    @ResponseBody
    public LayTableR list(Integer page, Integer limit, String master,String type) throws Exception {
        QueryWrapper<SaleOrder> ew = ConditionUtil.convert(master, new QueryWrapper<>());
        switch (type) {
            case "pricing":
                ew.apply("complet = 0");
                break;
            case "settlement":
                ew.apply("complet > 0 and amount = 0");
                break;
            case "processed":
                ew.apply("amount >= amounts");
                break;
            case "close":
                ew.apply("status = 1");
                break;
        }
        Page<SaleOrder> pageList = iSaleOrderService.listStat(new Page<>(page, limit), ew);
        return LayTableR.result(0, pageList.getTotal(), pageList.getRecords());
    }

    @RequestMapping("/close")
    @ResponseBody
    public R close(String id) throws Exception {
        if (id == null) {
            return R.error("参数异常");
        }
        try {
            iSaleOrderService.close(id);
        } catch (Exception e) {
            return R.error("关闭异常！ 请联系管理员");
        }
        return R.ok();
    }

    @RequestMapping("/price_nullify")
    @ResponseBody
    public R priceNullify(String detailsId) throws Exception {
        if (detailsId == null) {
            return R.error("参数异常");
        }
        try {
            iSaleOrderService.priceNullify(detailsId);
        } catch (BusinessException e){
            return R.error(e.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【系统异常】"+e);
            return R.error("作废异常！ "+e.getMessage());
        }
        return R.ok();
    }

    @RequestMapping("/settle_nullify")
    @ResponseBody
    public R settleNullify(String id) {
        if (id == null) {
            return R.error("参数异常");
        }
        try {
            iSaleOrderService.settleNullify(id);
        } catch (BusinessException e){
            return R.error(e.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【系统异常】"+e);
            return R.error("作废异常！ "+e.getMessage());
        }
        return R.ok();
    }

    @RequestMapping("/listSett")
    @ResponseBody
    public LayTableR listSett(Integer page, Integer limit, String key) throws Exception {
        QueryWrapper<SaleOrder> ew = new QueryWrapper<>();
        if (StringUtils.isNotBlank(key)) {
            ew.like("order_no", key);
        }
        ew.orderByDesc("create_time");
        Page<SaleOrder> pageList = iSaleOrderService.page(new Page<>(page, limit), ew);
        return LayTableR.result(0, pageList.getTotal(), pageList.getRecords());
    }

    @RequestMapping("/info")
    @ResponseBody
    public Object info(String masterId){
        SaleOrder saleOrder = iSaleOrderService.getById(masterId);
        List<SaleOrderDetails> detailsList = iSaleOrderDetailsService.list(new LambdaQueryWrapper<SaleOrderDetails>().eq(SaleOrderDetails::getMasterId, masterId));
        List<SettleOrderMasterNew> list = iSettleOrderMasterNewService.list(new LambdaQueryWrapper<SettleOrderMasterNew>().eq(SettleOrderMasterNew::getSaleOrderMasterId, masterId));
        Map<String, Double> amount = list.stream().collect(Collectors.groupingBy(SettleOrderMasterNew::getSaleOrderDetailId, Collectors.summingDouble(obj -> obj.getAmount().doubleValue())));
        Map<String, Double> qty = list.stream().collect(Collectors.groupingBy(SettleOrderMasterNew::getSaleOrderDetailId, Collectors.summingDouble(obj -> obj.getQty().doubleValue())));
        for (SaleOrderDetails details : detailsList) {
            String s = String.valueOf(details.getId());
            Double v = amount.get(s);
            if (v == null) {
                v = 0.0;
            }
            Double v1 = qty.get(s);
            if (v1 == null) {
                v1 = 0.0;
            }
            details.setSumAmount(String.valueOf(v));
            details.setSumQty(String.valueOf(v1));
        }
        saleOrder.setDetailsList(detailsList);
        return saleOrder;
    }

    @RequestMapping("/process_info")
    @ResponseBody
    public Object process_info(String detailsId) throws Exception{
        SaleOrderDetails orderDetails = iSaleOrderDetailsService.getById(detailsId);
        List<SaleOrderProcess> processList = iSaleOrderProcessService.list(new LambdaQueryWrapper<SaleOrderProcess>()
                .eq(SaleOrderProcess::getDetailsId, orderDetails.getMesId())
                .orderByAsc(SaleOrderProcess::getSerialNumber));
        if(orderDetails.getCompletFlag()){
            return processList;
        }else{
            SaleOrder saleOrder = iSaleOrderService.getById(orderDetails.getMasterId());
//            Customer customer = iCustomerService.getOne(new LambdaQueryWrapper<Customer>().eq(Customer::getCode, saleOrder.getCustomerCode()));
//            Product product = iProductService.getOne(new LambdaQueryWrapper<Product>().eq(Product::getCode, orderDetails.getCinvcode()));
            for(SaleOrderProcess saleOrderProcess : processList){

                ProcessPriceOrder priceOrder = iProcessPriceOrderService.getOne(new LambdaQueryWrapper<ProcessPriceOrder>()
                        .eq(ProcessPriceOrder::getCustomerId, saleOrder.getCustomerCode())
                        .eq(ProcessPriceOrder::getProductId, orderDetails.getCinvcode())
                        .eq(ProcessPriceOrder::getType, orderDetails.getType())
                        .eq(ProcessPriceOrder::getOrderProcessCode, saleOrderProcess.getOrderProcess()));

                if(priceOrder != null){
                    saleOrderProcess.setIoritaxcost(priceOrder.getOrderPrice());
                }
            }
        }
        return processList;
    }

    @RequestMapping("/process_info_new")
    @ResponseBody
    public LayTableR process_info_new(Integer page, Integer limit, String detailsId) throws Exception{
        if (StringUtils.isEmpty(detailsId)) {
            return LayTableR.result(0, 0, null);
        }
        return iSaleOrderProcessService.processInfo(page, limit, detailsId);
    }

    @RequestMapping("/process_info_price")
    @ResponseBody
    public R process_info_price(String detailsId,String processId) throws Exception{
        if (StringUtils.isEmpty(detailsId) || StringUtils.isEmpty(processId)) {
            return R.error();
        }
        try {
            iSaleOrderService.processInfoPrice(detailsId,processId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【系统异常】"+e);
            return R.error("添加失败！请联系管理员");
        }
        return R.ok();
    }

    @PostMapping("/price_set")
    @ResponseBody
    public R price_set(String detail){
        try {
            if(StringUtils.isEmpty(detail)){
                return R.error("参数异常");
            }
            SaleOrderDetails saleOrderDetails = JSON.parseObject(detail, SaleOrderDetails.class);
            if(saleOrderDetails == null){
                return R.error("参数异常");
            }
            List<SaleOrderProcess> processList = saleOrderDetails.getProcess();
            if(processList.size() < 1){
                return R.error("参数异常");
            }
            SaleOrderDetails orderDetails = iSaleOrderDetailsService.getById(saleOrderDetails.getId());
            if(orderDetails.getCompletFlag()){
                return R.error("已经订过价");
            }
            iSaleOrderProcessService.priceSet(saleOrderDetails,processList);
        }catch (BusinessException e){
            return R.error(e.getMsg());
        }catch (Exception e){
            e.printStackTrace();
            log.error("【系统异常】"+e);
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    @PostMapping("/order_settle")
    @ResponseBody
    public R order_settle(String settleData){
        try {
            if(StringUtils.isEmpty(settleData)){
                return R.error("参数异常");
            }
            SettleOrderMasterNew settleOrderMasterNew = JSON.parseObject(settleData, SettleOrderMasterNew.class);
            if(settleOrderMasterNew == null){
                return R.error("参数异常");
            }
            if(settleOrderMasterNew.getDetailList() == null){
                return R.error("参数异常");
            }
            SaleOrderDetails orderDetails = iSaleOrderDetailsService.getById(settleOrderMasterNew.getSaleOrderDetailId());
            if(orderDetails.getCompletFlag()==null || !orderDetails.getCompletFlag()){
                return R.error("销售订单还未定价");
            }
            iSaleOrderProcessService.orderSettle(settleOrderMasterNew.getSaleOrderMasterId(),settleOrderMasterNew.getSaleOrderDetailId(),settleOrderMasterNew);
        }catch (BusinessException e){
            return R.error(e.getMsg());
        }catch (Exception e){
            e.printStackTrace();
            log.error("【系统异常】"+e);
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    @RequestMapping("/download_templet")
    @ResponseBody
    public void templet(HttpServletResponse response) {
        try {
            //excel表头
            List<TitleEntity> titleList=new ArrayList<>();
            titleList.add(new TitleEntity("0",null,"销售订单期初导入模板",null));
            titleList.add(new TitleEntity("01","0","客户订单号",null));
            titleList.add(new TitleEntity("02","0","内部订单号-:",null));
            titleList.add(new TitleEntity("03","0","父级订单号",null));
            titleList.add(new TitleEntity("04","0","关联订单号",null));
            titleList.add(new TitleEntity("05","0","制单日期-:",null));
            titleList.add(new TitleEntity("06","0","客户编码-:",null));
            titleList.add(new TitleEntity("07","0","客户名称-:",null));
            titleList.add(new TitleEntity("08","0","部门编码-:",null));
            titleList.add(new TitleEntity("09","0","业务员",null));
            titleList.add(new TitleEntity("10","0","存货编码-:",null));
            titleList.add(new TitleEntity("11","0","存货名称-:",null));
            titleList.add(new TitleEntity("12","0","批号",null));
            titleList.add(new TitleEntity("13","0","类型-:",null));
            titleList.add(new TitleEntity("14","0","订单数量-:",null));
            List<CostEquipmentUsagerate> list = new ArrayList<>();
            ExcelTool excelTool = new ExcelTool("销售订单期初导入模板",20,20);
            List<Column>  titleData = excelTool.columnTransformer(titleList,"t_id","t_pid","t_content","t_fielName","0");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("销售订单期初导入模板.xlsx", "utf-8"));
            excelTool.exportExcel(titleData,list, response.getOutputStream(),true,true);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/add")
    @ResponseBody
    public R add(@RequestBody JSONObject jsonObject){
        if (null == jsonObject || jsonObject.isEmpty()){
            return R.error("未接收到数据！");
        }
        try {
            iSaleOrderService.add(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【系统异常】"+e);
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    @RequestMapping("/upd")
    @ResponseBody
    public R upd(@RequestBody JSONObject jsonObject){
        if (null == jsonObject || jsonObject.isEmpty()){
            return R.error("未接收到数据！");
        }
        try {
            iSaleOrderService.upd(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【系统异常】"+e);
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 发起结算
     */
    @RequestMapping("/settleHtml/{id}")
    public String addDetail(@PathVariable String id,Model model){
        model.addAttribute("id",id);
        return "sale_order/settlement";
    }

}

